import React, { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Button, Card, Table, Modal, Space, Popconfirm, Divider, Checkbox } from 'antd';
import { PlusOutlined, SyncOutlined } from '@ant-design/icons';
import { connect, FormattedMessage, useIntl } from 'umi';
import WarehseEntry from './warehseEntry';
import WhseBinEntry from './whseBinEntry';
import IconFont from '@/components/Iconfont';
import request from '@/utils/request';
import QuickMenu from '@/components/QuickMenu';
import ProTable from '@ant-design/pro-table';

const apiURL = '/api/services/app/Warehse/';
const apiURL2 = '/api/services/app/WhseBin/';

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [loading2, setLoading2] = useState(false);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageIndex2, setPageIndex2] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [totalCount2, setTotalCount2] = useState(0);
  const [CurrWhse, setCurrWhse] = useState<any>({ warehouseCode: 'WGJ' });
  const [dataSource, setDataSource] = useState([]);
  const [dataSource2, setDataSource2] = useState([]);
  const [visible, setVisible] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [record, setRecord] = useState<any>(null);
  const [record2, setRecord2] = useState<any>(null);
  const [whseTypeOption, setWhseType] = useState<any[]>([]);
  const formRef = useRef<any>();
  const intl = useIntl();

  useEffect(() => {
    fetchWhseType();
    fetchDatas();    
  }, [pageIndex]);
  const fetchWhseType = async () => {
    const response = await request('/api/services/app/Category/GetTreeListAsync', {
      method: 'GET',
      params: { layout: 'warehouseType' },
    });
    if(response.result == null) return;
    const arr: any = [];
    response.result.forEach((element: any) => {
      arr.push({
        label: element.categoryName,
        value: element.categoryIndex,
      });
    });
    setWhseType(arr);
  };
  const fetchDatas = async () => {
    try {
      setLoading(true);
      const skip = (pageIndex - 1) * pageSize;
      const params = {
        skipCount: skip,
        maxResultCount: pageSize,
      };
      const response = await request(apiURL + 'GetList', {
        method: 'GET',
        params,
      });
      setDataSource(response.result?.items);
      setTotalCount(response.result?.totalCount);
      setCurrWhse(response.result?.items[0]);
      setLoading(false);
      switchModal(false);
    } catch (error) {
      console.log(error);
    }
  };

  const fetchDatas2 = async () => {
    try {
      setLoading2(true);
      const skip = (pageIndex2 - 1) * pageSize;
      const params = {
        skipCount: skip,
        maxResultCount: pageSize,
        whse: CurrWhse.warehouseCode,
      };
      const response = await request(apiURL2 + 'GetList', {
        method: 'GET',
        params,
      });
      setDataSource2(response.result?.items);
      setTotalCount2(response.result?.totalCount);
      setLoading2(false);
      switchModal2(false);
    } catch (error) {
      console.log(error);
    }
  };

  const switchModal = (visible: boolean, record: any = null) => {
    setVisible(visible);
    setRecord(record);
  };

  const switchModal2 = (visible2: boolean, record2: any = null) => {
    setVisible2(visible2);
    setRecord2(record2);
  };

  const handleDelete = async (id: any, control: string = 'Warehse') => {
    await request((control === 'Warehse' ? apiURL : apiURL2) + 'DelBatch', {
      method: 'POST',
      data: [id],
    });
    if (control === 'Warehse') fetchDatas();
    else fetchDatas2();
  };

  const columns = [
    {
      width: 30,
      render: () => <IconFont type="icon-package" />,
    },
    {
      title: <FormattedMessage id="pages.warehouseCode" />,
      dataIndex: 'warehouseCode',
      key: 'warehouseCode',
    },
    {
      title: <FormattedMessage id="pages.warehouseDesc" />,
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: <FormattedMessage id="pages.warehouseType" />,
      dataIndex: 'warehouseType',
      key: 'warehouseType',
      valueType: 'select',
      fieldProps: {
        options: whseTypeOption,
      },
    },
    {
      title: <FormattedMessage id="pages.operation" />,
      hideInSearch: true,
      render: (record: any) => (
        <span>
          <Popconfirm
            key="1"
            title={intl.formatMessage({ id: 'pages.delete?' })}
            onConfirm={() => handleDelete(record.id)}
          >
            <a>
              <FormattedMessage id="pages.delete" />
            </a>
          </Popconfirm>
          <Divider key="2" type="vertical" />
          <a key="3" onClick={() => switchModal(true, record)}>
            <FormattedMessage id="pages.edit" />
          </a>
        </span>
      ),
    },
  ];

  const columns2 = [
    {
      width: 30,
      render: () => <IconFont type="icon-database" />,
    },
    {
      title: <FormattedMessage id="pages.warehouseCode" />,
      dataIndex: 'warehouseCode',
      key: 'warehouseCode',
    },
    {
      title: <FormattedMessage id="pages.binNum" />,
      dataIndex: 'binNum',
      key: 'binNum',
    },
    {
      title: <FormattedMessage id="pages.binDesc" />,
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: <FormattedMessage id="pages.nonNettable" />,
      dataIndex: 'nonNettable',
      key: 'nonNettable',
      render: (text: boolean) => <Checkbox checked={text} />,
    },
    {
      title: <FormattedMessage id="pages.invalid" />,
      dataIndex: 'inActive',
      key: 'inActive',
      render: (text: boolean) => <Checkbox checked={text} />,
    },
    {
      title: <FormattedMessage id="pages.operation" />,
      render: (record: any) => (
        <span>
          <Popconfirm
            title={intl.formatMessage({ id: 'pages.delete?' })}
            onConfirm={() => handleDelete(record.id, 'WhseBin')}
          >
            <a>
              <FormattedMessage id="pages.delete" />
            </a>
          </Popconfirm>
          <Divider type="vertical" />
          <a onClick={() => switchModal2(true, record)}>
            <FormattedMessage id="pages.edit" />
          </a>
        </span>
      ),
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card
        title={<FormattedMessage id="pages.warehouse" />}
        extra={[
          <Space key="s1">
            <QuickMenu path="/part/warehse" icon="icon-library" title="pages.WarehseManage" />
            <Button type="primary" onClick={() => switchModal(true)} icon={<PlusOutlined />}>
              <span>
                <FormattedMessage id="pages.new" />
              </span>
            </Button>
            <Button type="ghost" onClick={() => {fetchWhseType();fetchDatas()}} icon={<SyncOutlined />}>
              <span>
                <FormattedMessage id="pages.refresh" />
              </span>
            </Button>
          </Space>,
        ]}
      >
        <ProTable
          rowKey="id"
          size="small"
          toolBarRender={false}
          loading={loading}
          columns={columns}
          dataSource={dataSource}
          search={false}
          onRow={(record) => {
            return {
              onClick: () => {
                setCurrWhse(record);
                fetchDatas2();
              },
            };
          }}
          pagination={{
            onChange: (page) => {
              setPageIndex(page);
            },
            pageSize,
            total: totalCount,
          }}
        />
      </Card>
      <Card
        title={CurrWhse?.description}
        extra={[
          <Space key="s2">
            <Button
              type="primary"
              disabled={CurrWhse == null}
              onClick={() => switchModal2(true)}
              icon={<PlusOutlined />}
            >
              <span>
                <FormattedMessage id="pages.new" />
              </span>
            </Button>
            <Button type="ghost" onClick={() => fetchDatas2()} icon={<SyncOutlined />}>
              <span>
                <FormattedMessage id="pages.refresh" />
              </span>
            </Button>
          </Space>,
        ]}
      >
        <Table
          rowKey="id"
          size="small"
          loading={loading2}
          columns={columns2}
          dataSource={dataSource2}
          pagination={{
            onChange: (page) => {
              setPageIndex2(page);
            },
            pageSize,
            total: totalCount2,
          }}
        />
      </Card>
      <Modal
        title={<FormattedMessage id="WarehouseEdit" />}
        visible={visible}
        destroyOnClose={true}
        onCancel={() => switchModal(false)}
        footer={false}
      >
        <WarehseEntry id={record?.id} fetchData={fetchDatas} />
      </Modal>
      <Modal
        title={<FormattedMessage id="BinEdit" />}
        visible={visible2}
        destroyOnClose={true}
        onCancel={() => switchModal2(false)}
        footer={false}
      >
        <WhseBinEntry id={record2?.id} fetchData={fetchDatas2} WareHse={CurrWhse} />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
